import TRTC from 'trtc-js-sdk'
import apiMod from '@/apiMod/index'
import { getStore } from '@/utils/store'

export default class trtcCall {
	userId: string
	client: any
	roomId: number
	localStream: any
	remoteStream: any
	constructor(userId = '100', roomId = 1) {
		this.userId = userId
		this.roomId = roomId
	}

	init() {
		TRTC.checkSystemRequirements().then((res) => {
			if (res.result) {
				this.initJoinRoom()
				// 推送事件：发送通话
			} else {
				console.log('设备不支持')
			}
		})
	}
	async initJoinRoom() {
		await this.clientInit()
		if (this.client != null) {
			await this.joinRoom()
			// 推送事件：发送通话
		}
	}
	// 认证
	async clientInit() {
		const sdkAppId = 1400787426
		const userInfo = getStore('userInfo') || {}
		const { data } = await apiMod.view_sys_liteAv_sign(userInfo.id)
		// 创建流
		const options: any = {
			mode: 'rtc',
			sdkAppId: sdkAppId,
			userSig: data,
			userId: this.userId,
		}
		this.client = TRTC.createClient(options) //创建一个用户对象
		await this.subscribeStream()
	}

	// 订阅远端流
	subscribeStream = () => {
		// 监听回调，当远端流加入时使用
		this.client.on('stream-added', (evt) => {
			//订阅远端流
			this.client.subscribe(evt.stream)
		})
		this.client.on('stream-removed', (evt) => {
			console.log(evt, 'stream-removed')
		})
	}
	// 加入房间 房间 Id，不能重复
	joinRoom = async () => {
		try {
			await this.createStream()
			await this.client.join({
				roomId: this.roomId,
			})
			console.log('加入房间成功')
			await this.publishStream()
		} catch (err) {
			console.log('进房失败', err)
		}
	}
	// 发布本地流
	createStream = async () => {
		// 本地推流
		this.localStream = TRTC.createStream({
			userId: this.userId,
			audio: true,
			video: true,
		})
		// 初始化本地音视频流
		try {
			await this.localStream.initialize()
			let videoElement = document.getElementsByTagName('video')[0]
			videoElement.srcObject = this.localStream.mediaStream_
			videoElement.autoplay = true
		} catch (error) {
			switch (error.name) {
				case 'NotReadableError':
					console.log('时无法访问摄像头/麦克风，请确保当前没有其他应用请求访问摄像头/麦克风，并重试')
					break
				default:
					console.error(error)
					break
			}
		}
	}
	// 发布
	publishStream = () => {
		this.client.publish(this.localStream)
	}
	// 摄像头打开关闭控制
	videoSwitch = (open = true) => {
		if (this.localStream) {
			if (open) {
				this.localStream.muteVideo()
			} else {
				this.localStream.unmuteVideo()
			}
		}
	}
	voiceSwitch = (open = true) => {
		if (this.localStream) {
			if (open) {
				this.localStream.muteAudio()
			} else {
				this.localStream.unmuteAudio()
			}
		}
	}
	// 退出房间
	outRoom = () => {
		this.client
			.leave()
			.then(() => {
				console.log('退房成功')
				this.localStream.stop() //停止本地流，关闭本地流内部的音视频播放器
				this.localStream.close() // 关闭本地流，释放摄像头和麦克风访问权限
				this.client.enableAudioVolumeEvaluation(-1) // 停止获取流量
			})
			.catch((error) => {
				console.error('退房失败 ' + error) // 错误不可恢复，需要刷新页面
			})
	}
	// 判断是否是已加入的远端流,没有在房间返回-1
	isremoteStream = (userId) => {
		let remoteStream = this.remoteStream
		for (let i = 0; i < remoteStream.length; i++) {
			if (remoteStream[i].getUserId() == userId) return i
		}
		return -1
	}
}
